#include <windows.h>

#include "window.h"
#include "support.h"

HWINEVENTHOOK evt_hook;

static VOID CALLBACK event_proc(HWINEVENTHOOK, DWORD, HWND, LONG, LONG, DWORD, DWORD);
static void install_event_hook(UINT event);

void install_event_handlers()
{
	install_event_hook(EVENT_SYSTEM_MOVESIZEEND);
	install_event_hook(EVENT_SYSTEM_FOREGROUND);
	
	install_event_hook(EVENT_OBJECT_CREATE);
	install_event_hook(EVENT_OBJECT_DESTROY);
	install_event_hook(EVENT_OBJECT_NAMECHANGE);
}

void free_event_handlers()
{
	UnhookWinEvent(evt_hook);
}

static void install_event_hook(UINT event)
{
	evt_hook = SetWinEventHook(
		event,
		event,
		0,
		(WINEVENTPROC)event_proc,
		0, 0,
		WINEVENT_OUTOFCONTEXT
	);
	if(!evt_hook) 
		fatal("Event error");
}

static void print_wnd(HWND wnd)
{
	if(wnd)
	{
		char *t = alloc_title(wnd);
		char buf[256];
		
		GetClassName(wnd, buf, 256);
		printf("%x; Class: \"%s\", Title: \"%s\"\n", wnd, buf, t);
		free(t);
		
		printf("Parent:\n");
		print_wnd(GetParent(wnd));
	}
	else
		printf("(Null)\n");
}

static VOID CALLBACK event_proc(
	HWINEVENTHOOK hook,
	DWORD event,
	HWND wnd,
	LONG object,
	LONG child,
	DWORD thread,
	DWORD time )
{
	if(event == EVENT_OBJECT_DESTROY)
	{
		/*
			We can't get any info about the window, it's already been destroyed.
			Just remove it if it's on any toolbars.
		*/
		SendMessage(main_window, UntrackMsg, (WPARAM)wnd, 0);
		return;
	}
	
	if(should_ignore(wnd))
		return;
	
	if(event == EVENT_OBJECT_NAMECHANGE)
	{
		SendMessage(main_window, TrackMsg, (WPARAM)wnd, 0);
	}
	else if(event == EVENT_OBJECT_CREATE)
	{
		SendMessage(main_window, TrackMsg, (WPARAM)wnd, 0);
	}
	else if(event == EVENT_SYSTEM_MOVESIZEEND)
	{
		SendMessage(main_window, TrackMsg, (WPARAM)wnd, 0);
	}
	else if(event == EVENT_SYSTEM_FOREGROUND)
	{
		SendMessage(main_window, ActivateMsg, (WPARAM)wnd, 0);
	}
}

